# -*- coding:utf8 -*
from core import nmt
import numpy as np
import jieba
from nltk.tokenize import sent_tokenize
import pythoncom
# 文字提取  文字转吗   文字转换  文字保存
lr = 1e-3
src_max_seq_len = 40

import os
def parserfile(filename, userid):
    if not os.path.exists("../upload/"+str(userid)):
        os.mkdir("../upload/"+str(userid))
    if not os.path.exists("../output/"+str(userid)):
        os.mkdir("../output/"+str(userid))
    #file process
    s=0
    endfix = filename.rsplit('.', 2)[-1]
    try:
        if endfix=='doc':
            parserdoc(filename,userid)
        elif endfix=='docx':
            parserdocx(filename,userid)
        elif endfix=='xls':
            parserxls(filename,userid)
        elif endfix=='xlsx':
            parserxlsx(filename,userid)
        elif endfix=='ppt':
            parserppt(filename,userid)
        elif endfix=='pptx':
            parserpptx(filename,userid)
        elif endfix=='txt':
            parsetxt(filename,userid)
        elif endfix=='pdf':
            parserpdf(filename,userid)
        elif endfix=='jpg' or endfix=='jpeg' or endfix=='png' or endfix=='bmp':
            parserpic(filename,userid)
        else:
            return 0
    except Exception as e:
        print(e)
        s=1
    if s:
        return 0
    return 1

def opredict(text, httpc):
    temp = api.getre(text, httpc)
    s = 0
    try:
        s = str(temp['trans_result'][0]['dst'])
    except:
        s = text

    return s

from untils import tools, api

def picpredict(f, ):
    re = api.getpicre(f)
    return re

def olpredict(model, sess, en_word2id, en_id2word, ch_word2id, ch_id2word, x):
    X = nmt.segment(x, jieba.cut)
    X = nmt.transform(X, en_word2id)
    X = nmt.padding(X, src_max_seq_len)
    [rows, cols] = X.shape
    print(rows, cols)  # 用于修补模型异常
    for i in range(rows):
        for j in range(cols):
            if (X[i, j] > 59999):
                X[i, j] = 1000
    X_len = np.sum((X > 0), axis=1)
    translations = sess.run(model.translations,
                            feed_dict={model.X: X,
                                       model.Y_out: [[]],
                                       model.Y_in: [[]],
                                       model.X_len: X_len,
                                       model.Y_in_len: [],
                                       model.Y_out_len: [],
                                       model.lr: lr,
                                       model.dropout: 0.})
    translations = nmt.transform2word(translations, ch_id2word)
    return translations[0].replace("<PAD>", "")

# doc文件
def parserdoc(filename, userid):
    from win32com import client
    from docx import Document
    import os
    dfile = Document()
    path_original = "/upload/" + str(userid) + "/" + filename
    pythoncom.CoInitialize()  # 加上的
    word = client.Dispatch('Word.Application')
    pythoncom.CoInitialize()  # 加上的
    print(path_original)
    doc = word.Documents.Open(os.path.dirname(os.getcwd()) + path_original)  # 目标路径下的文件
    # 将文件转存至同名文件夹下重命名为 rename_+temp+docx.docx
    filenamet = filename + "_+temp+docx.docx"
    path_final = os.path.dirname(os.getcwd()) + "/upload/" + str(userid) + "/" + filenamet
    print(path_final)
    doc.SaveAs(path_final, 16)  # 转化后路径下的文件
    doc.Close()
    word.Quit()
    dfile = parserdocx(filenamet, userid, 0)
    dfile.save("../output/" + str(userid) + "/" + filename)
    os.remove(path_final)
    pass

# docx文件
def parserdocx(filename, userid, local=1):
    from docx import Document
    import copy
    httpClient = 0
    dfile = Document("../upload/" + str(userid) + "/" + filename)
    # 通用文本翻译
    for i in range(len(dfile.paragraphs)):
        left = ""  # 剩余中文
        remain = ""  # 剩余英文
        index = 0
        pg = copy.copy((dfile.paragraphs[i]))
        runs = copy.deepcopy(dfile.paragraphs[i].runs)
        # 简易文本处理
        for p in range(len(runs)):
            if p < index:
                continue
            if p == len(runs) - 1:
                if len(left) == 0:
                    pass
                elif left[-1] == "。" or left[-1] == "!" or left[-1] == "?" or left[-1] == ")":
                    pass
                else:
                    left += "。"
                runs[p].text = left + tools.filterreg(opredict(runs[p].text.strip(), httpClient))
                if len(runs[p].text) == 0:
                    pass
                elif runs[p].text[-1] == "!" or runs[p].text[-1] == "?" or runs[p].text[-1] == "。":
                    pass
                else:
                    runs[p].text += "。"
                left = ""
                continue
            if (not runs[p].text) or runs[p].text == "" or runs[p].text == " ":
                continue
            temp = tools.splitbyreg(runs[p].text)
            if temp != 0:  # 有终结符
                for n in range(len(temp) - 1):
                    if temp[n] == "" or temp[n] == " ":
                        continue
                    left += opredict(temp[n], httpClient)
                    left += "。"
                    runs[p].text = str(runs[p].text.strip()).replace(temp[n].strip(), "", 1)
                if temp[-1] == "" or temp[-1] == " ":
                    runs[p].text = left
                    left = ""
                else:
                    remain = runs[p].text
                    [index, remain, runs] = tools.findnext(p, remain, runs)
                    # remain存了一条完整的英文句子  index表示找到那个run
                    chremain = opredict(remain, httpClient)
                    remain += "。"
                    [left, runs] = tools.funcnext(chremain, p, index, left, runs, httpClient)
                    remain = ""
                    # 需要处理文本和中间跨越的run
            else:
                # 无终结符  findnext
                remain = runs[p].text
                [index, remain, runs] = tools.findnext(p, remain, runs)
               # print(remain)
                chremain = opredict(remain, httpClient)
                [left, runs] = tools.funcnext(chremain, p, index, left, runs, httpClient)
                remain = ""
        if len(runs) != 0:
            runs[-1].text += left
        for r in range(len(runs)):
            if not runs[r].text and (not pg.runs[r].text):
                continue
            pg.runs[r].text = runs[r].text

    # 目录和文本框处理
    # catalog
    children = dfile.element.body
    for e in children.getchildren():
        if e.tag.endswith("sdt"):
            for s in e.iter():
                if s.tag.endswith("sdtContent"):
                    for t in s.getchildren():
                        if t.tag.endswith("main}p"):
                            for x in t.getchildren():
                                if x.tag.endswith("main}r"):
                                    #print(x.text)
                                    if x.text.isalpha():
                                        x.text = opredict(x.text, 0)
    # textbox
    children = dfile.element.body.iter()
    catalog_iters = []
    runs_p = []
    for child in children:
        # 通过类型判断目录
        if child.tag.endswith(('AlternateContent')):
            for r in child.iter():
                if r.tag.endswith("Choice"):
                    for t in r.iter():
                        if t.tag.endswith('txbxContent'):
                            for s in t.getchildren():
                                if s.tag.endswith("main}p"):
                                    runs_p.append([])
                                    for m in s.getchildren():
                                        if m.tag.endswith("main}r"):
                                            runs_p[-1].append(m)
                                            #print(m.text)
                                            m.text = opredict(m.text, 0)
                elif r.tag.endswith("Fallback"):
                    for t in r.iter():
                        if t.tag.endswith('txbxContent'):
                            for s in t.getchildren():
                                if s.tag.endswith("main}p"):
                                    runs_p.append([])
                                    for m in s.getchildren():
                                        if m.tag.endswith("main}r"):
                                            m.text = ""
                else:
                    pass

    # 表格处理、
    tables = dfile.tables  # 获取文件中的表格集
    for table in tables[:]:
        for i, row in enumerate(table.rows[:]):  # 读每行
            for cell in row.cells[:]:  # 读一行中的所有单元格
                cell.text = opredict(cell.text, 0)
    # 页眉和页脚
    sections = dfile.sections
    for s in sections:
        for p in s.header.paragraphs:
            for r in p.runs:
                if r.text.isdigit() or len(r.text) == 0:
                    continue
                r.text = opredict(r.text, 0)
        for p in s.footer.paragraphs:
            for r in p.runs:
                if r.text.isdigit() or len(r.text) == 0:
                    continue
                r.text = opredict(r.text, 0)
    if local != 1:  # 外部调用
        return dfile
    else:
        dfile.save("../output/" + str(userid) + "/" + filename)

# ppt文件
def parserppt(filename, userid):
    import os
    from win32com import client
    from pptx import Presentation
    dfile = Presentation()
    path_original = "/upload/" + str(userid) + "/" + filename
    pythoncom.CoInitialize()  # 加上的
    ppt = client.Dispatch('PowerPoint.Application')
    pythoncom.CoInitialize()  # 加上的
    print(path_original)
    pps = ppt.Presentations.Open(os.path.dirname(os.getcwd()) + path_original)  # 目标路径下的文件
    # 将文件转存至同名文件夹下重命名为 rename_+temp+docx.docx
    filenamet = filename + "_+temp+pptx.pptx"
    path_final = os.path.dirname(os.getcwd()) + "/upload/" + str(userid) + "/" + filenamet
    print(path_final)
    pps.SaveAs(path_final)  # 转化后路径下的文件
    pps.Close()
    ppt.Quit()
    dfile = parserpptx(filenamet, userid, 0)
    dfile.save("../output/" + str(userid) + "/" + filename)
    os.remove(path_final)

# pptx文件
def parserpptx(filename, userid, local=1):
    from pptx import Presentation
    dfile = Presentation("../upload/" + str(userid) + "/" + filename)
    for slide in dfile.slides:
        for shape in slide.shapes:
            if not shape.has_text_frame:
                continue
            for paragraph in shape.text_frame.paragraphs:
                for run in paragraph.runs:
                    if type(run.text) == int or type(run.text) == float:
                        continue
                    if not run.text.isdigit():
                        print(run.text)
                        run.text = opredict(run.text, 0)
    if local == 1:
        dfile.save('../output/' + str(userid) + "/" + filename)
    else:
        return dfile

# txt文件
def parsetxt(filename, userid):
    file = open("../upload/" + str(userid) + "/" + filename, encoding='UTF-8')
    t = file.read()
    sentences = sent_tokenize(t)
    file.close()
    ofile = open("../output/" + str(userid) + "/" + filename, "a+", encoding="utf-8")
    for t in sentences:
        ofile.write(opredict(t, 0) + "\n")
    ofile.close()

# xls文件
def parserxls(filename, userid):
    import xlrd
    from xlutils.copy import copy
    rf = xlrd.open_workbook("../upload/" + str(userid) + "/" + filename)  # 打开xls文件
    df = copy(rf)  # 利用xlutils.copy下的copy函数复制
    for t in range(len(rf.sheets())):
        sheet = rf.sheets()[t]
        df.get_sheet(t).name = opredict(sheet.name, 0)
        row = sheet.nrows
        col = sheet.ncols
        for i in range(row):
            for j in range(col):
                if type(sheet.cell(i, j).value) == int or type(sheet.cell(i, j).value) == float:
                    continue
                if not sheet.cell(i, j).value.isdigit():
                    df.get_sheet(t).write(i, j, opredict(sheet.cell(i, j).value, 0))
    df.save('../output/' + str(userid) + "/" + filename)
    pass

# xlsx文件 完成
def parserxlsx(filename, userid):
    from openpyxl import load_workbook
    dfile = load_workbook("../upload/" + str(userid) + "/" + filename, data_only=True)
    for i in range(len(dfile.sheetnames)):
        t = dfile.sheetnames[i]
        if type(t) == int or type(t) == float:
            continue
        if not t.isdigit():
            dfile.worksheets[i].title = opredict(t, 0)
    for sheete in dfile.sheetnames:
        sheet = dfile.get_sheet_by_name(sheete)
        row = sheet.max_row
        col = sheet.max_column
        for i in range(row):
            for j in range(col):
                if type(sheet.cell(i + 1, j + 1).value) == int or type(sheet.cell(i + 1, j + 1).value) == float:
                    continue
                if not sheet.cell(i + 1, j + 1).value.isdigit():
                    sheet.cell(i + 1, j + 1).value = opredict(sheet.cell(i + 1, j + 1).value, 0)
    dfile.save('../output/' + str(userid) + "/" + filename)

def parserpdf(filename, userid):
    from win32com import client
    import os
    path_original = "/upload/" + str(userid) + "/" + filename
    pythoncom.CoInitialize()  # 加上的
    word = client.Dispatch('Word.Application')
    word = client.gencache.EnsureDispatch('Word.Application')
    pythoncom.CoInitialize()  # 加上的
    print(path_original)
    doc = 3
    try:
        doc = word.Documents.Open(os.path.dirname(os.getcwd()) + path_original)  # 目标路径下的文件
    except Exception as e:
        print(e)
        #ocr pdf
        pass

    if doc == 3:
        #ocr
        dfile = parserpdf_ocr(filename, userid, 0)
        dfile.save('../output/' + str(userid) + "/" + filename)
        dfile.close()
    else:
        #没问题
        try:
            doc.SaveAs(os.path.dirname(os.getcwd())+"/upload/" + str(userid) + "/" + filename+".docx", 16)
        except:
            doc.Close()
            word.Quit()
            return
        finally:
            doc.Close()
            word.Quit()
        parserdocx(filename+".docx", userid, 1)
        os.remove(os.path.dirname(os.getcwd()) + "/upload/" + str(userid) + "/" + filename + ".docx")
        pythoncom.CoInitialize()  # 加上的
        word = client.Dispatch('Word.Application')
        #word = DispatchEx("Word.Application")
        pythoncom.CoInitialize()  # 加上的
        # word = client.gencache.EnsureDispatch('Word.Application')
        doc = word.Documents.Open(os.path.dirname(os.getcwd())+"/output/" + str(userid) + "/" + filename+".docx")
        doc.SaveAs(os.path.dirname(os.getcwd())+"/output/" + str(userid) + "/" + filename, 17)
        doc.Close()
        word.Quit()
        os.remove(os.path.dirname(os.getcwd()) + "/output/" + str(userid) + "/" + filename+".docx")
        print("finished!")

def parserpdf_ocr(filename, userid, local =1):
    from wand.image import Image
    import os
    image_pdf = Image(filename=os.path.dirname(os.getcwd())+"/upload/" + str(userid) + "/" + filename, resolution=300)
    image_jpeg = image_pdf.convert('jpg')
    req_image = []
    for img in image_jpeg.sequence:
        img_page = Image(image=img)
        req_image.append(img_page.make_blob('jpg'))
    # 遍历req_image,保存为图片文件
    i = 0
    s = filename.split(".pdf")[0]
    #创建文件夹
    if not os.path.exists(os.path.dirname(os.getcwd())+"/upload/"+str(userid)+"/"+s):
        os.mkdir(os.path.dirname(os.getcwd())+"/upload/"+str(userid)+"/"+s)
    for img in req_image:
        ff = open(os.path.dirname(os.getcwd())+"/upload/"+str(userid)+"/"+s+"/"+str(i) + '.jpg', 'w+b')
        ff.write(img)
        ff.close()
        i += 1
    for t in range(i-1):
        parserpic(s+"/"+str(t) + '.jpg', userid, 0)
    import glob
    import fitz
    import os
    import shutil
    pdf = fitz.open()
    for img in sorted(glob.glob("../upload/"+str(userid)+"/"+s+"/*")):  # 读取图片，确保按文件名排序
        print(img)
        imgdoc = fitz.open(img)                 # 打开图片
        pdfbytes = imgdoc.convertToPDF()        # 使用图片创建单页的 PDF
        imgpdf = fitz.open("pdf", pdfbytes)
        pdf.insertPDF(imgpdf)                   # 将当前页插入文档
    if os.path.exists(os.path.dirname(os.getcwd())+"/upload/"+str(userid)+"/"+s):
        shutil.rmtree(os.path.dirname(os.getcwd())+"/upload/"+str(userid)+"/"+s)
    if local == 1:
        pdf.save('../output/' + str(userid) + "/" + filename)                   # 保存pdf文件
        pdf.close()
    else:
        return pdf

# jpg/jpeg/png/bmp <4M
def parserpic(filename, userid, local=1):
    from PIL import Image
    from PIL import ImageDraw
    from PIL import ImageFont
    import base64
    f = open("../upload/" + str(userid) + "/" + filename, 'rb')
    ft = base64.b64encode(f.read())
    ocresult = picpredict(ft)
    ocresult = ocresult['words_result']  # 这是个list({loc:{},words:()})
    f.close()
    img = Image.open("../upload/" + str(userid) + "/" + filename)
    img = img.convert("RGB")  # 把图片强制转成RGB
    # 图片宽度
    width = img.size[0]
    # 图片高度
    height = img.size[1]
    """对每个坐标区域颜色修改-背景色"""
    remain=""
    for i in ocresult:
        location = i['location']  # dict left top width height,
        location = list(map(int, [location['left'], location['top'], location['width'], location['height']]))
        words = i['words']  # 一句话
        index = 0
        word_s = tools.splitbyreg(words)
        word_s[0] = remain +word_s[0]
        s = ''
        if word_s != 0:  # has  trans
            segt = word_s[-1]
            for seg in word_s:
                if seg==segt:
                    remain = segt
                    break
                s = s + str(opredict(seg, 0)) + words[len(seg) + index]
                index = index + len(seg)
        else:  # no reg  to trans
            s = opredict(words, 0)

        """右边边界向右平移1/5高度，若识别区域右边界为图片右边界则不作平移"""
        if location[2] * 1.2 + location[0] > width:
            location[2] = int(width - location[0])
        else:
            location[2] = int(location[2] * 1.2)
        """计算背景颜色"""
        RGB_1 = []
        RGB_2 = []
        RGB_3 = []
        for x in range(location[2]):
            for y in range(location[3]):
                """获取边框上的全部点的颜色"""
                data = (img.getpixel((location[0] + x, location[1] + y)))
                # 获取坐标颜色R值
                RGB_1.append(data[0])
                # 获取坐标颜色g值
                RGB_2.append(data[1])
                # 获取坐标颜色b值
                RGB_3.append(data[2])
        # 按从小到大排序
        RGB_1.sort()
        RGB_2.sort()
        RGB_3.sort()
        # 取出颜色中间值
        RGB_1 = RGB_1[int(len(RGB_1) / 2)]
        RGB_2 = RGB_2[int(len(RGB_2) / 2)]
        RGB_3 = RGB_3[int(len(RGB_3) / 2)]
        # 组成最可能的背景色
        RGB_data = (RGB_1, RGB_2, RGB_3)
        """根据背景色选择文字颜色"""
        if (RGB_1 * 0.299 + RGB_2 * 0.578 + RGB_3 * 0.114) >= 192:  # 浅色
            words_colour = (0, 0, 0)  # 设置文字颜色为黑色
        else:
            words_colour = (255, 255, 255)  # 设置文字颜色为白色
        """填充颜色"""
        for x in range(location[2]):
            for y in range(location[3]):
                """获取边框上的全部点的颜色"""
                img.putpixel((location[0] + x, location[1] + y), RGB_data)
        """填充文字"""
        """写字位置下调五分之一高度"""
        #location[1] = int(location[1] * 7.2/ 7)
        """设置字体大小"""
        font_size = int(location[3] * 6/ 7)
        """字体采用himalaya"""
        font = ImageFont.truetype(r"simsun.ttc", font_size, encoding='utf-8')
        # 画图
        draw = ImageDraw.Draw(img)
        draw.text((location[:2]), s, words_colour, font=font)  # 设置文字位置/内容/颜色/字体
        draw = ImageDraw.Draw(img)
        # 另存图片
    if local ==1:
        img.save('../output/' + str(userid) + "/" + filename)  # 保存图片
    else:
        img.save("../upload/" + str(userid) + "/" + filename)

import copy
def exchangerunformat(run1, run2):
    run1.bold,run2.bold=run2.bold,run1.bold
    run1.italic, run2.italic = run2.italic, run1.italic
    run1.style, run2.style = run2.style, run1.style
    run1.underline, run2.underline = run2.underline, run1.underline

    # run2.font.all_caps, run1.font.all_caps = run1.font.all_caps, temp.all_caps
    run2.font.all_caps, run1.font.all_caps = run1.font.all_caps, run2.font.all_caps
    # run2.font.bold, run1.font.bold = run1.font.bold, temp.bold
    run2.font.bold, run1.font.bold = run1.font.bold, run2.font.bold
    # run2.font.cs_italic, run1.font.cs_italic = run1.font.cs_italic, temp.cs_italic
    run2.font.cs_italic, run1.font.cs_italic = run1.font.cs_italic, run2.font.cs_italic
    # run2.font.cs_bold, run1.font.cs_bold = run1.font.cs_bold, temp.cs_bold
    run2.font.cs_bold, run1.font.cs_bold = run1.font.cs_bold, run2.font.cs_bold
    # run2.font.double_strike, run1.font.double_strike = run1.font.double_strike, temp.double_strike
    run2.font.double_strike, run1.font.double_strike = run1.font.double_strike, run2.font.double_strike
    # run2.font.emboss, run1.font.emboss = run1.font.emboss, temp.emboss
    run2.font.emboss, run1.font.emboss = run1.font.emboss, run2.font.emboss
    # run2.font.hidden, run1.font.hidden = run1.font.hidden, temp.hidden
    run2.font.hidden, run1.font.hidden = run1.font.hidden, run2.font.hidden
    # run2.font.highlight_color, run1.font.highlight_color = run1.font.highlight_color, temp.highlight_color
    run2.font.highlight_color, run1.font.highlight_color = run1.font.highlight_color, run2.font.highlight_color
    # run2.font.italic, run1.font.italic = run1.font.italic, temp.italic
    run2.font.italic, run1.font.italic = run1.font.italic, run2.font.italic
    # run2.font.imprint, run1.font.imprint = run1.font.imprint, temp.imprint
    run2.font.imprint, run1.font.imprint = run1.font.imprint, run2.font.imprint
    # run2.font.math, run1.font.math = run1.font.math, temp.math
    run2.font.math, run1.font.math = run1.font.math, run2.font.math
    # run2.font.name, run1.font.name = run1.font.name, temp.name
    run2.font.name, run1.font.name = run1.font.name, run2.font.name
    # run2.font.no_proof, run1.font.no_proof = run1.font.no_proof, temp.no_proof
    run2.font.no_proof, run1.font.no_proof = run1.font.no_proof, run2.font.no_proof
    # run2.font.outline, run1.font.outline = run1.font.outline, temp.outline
    run2.font.outline, run1.font.outline = run1.font.outline, run2.font.outline
    # run2.font.rtl, run1.font.rtl = run1.font.rtl, temp.rtl
    run2.font.rtl, run1.font.rtl = run1.font.rtl, run2.font.rtl
    # run2.font.shadow, run1.font.shadow = run1.font.shadow, temp.shadow
    run2.font.shadow, run1.font.shadow = run1.font.shadow, run2.font.shadow
    # run2.font.size, run1.font.size = run1.font.size, temp.size
    run2.font.size, run1.font.size = run1.font.size, run2.font.size
    # run2.font.small_caps, run1.font.small_caps = run1.font.small_caps, temp.small_caps
    run2.font.small_caps, run1.font.small_caps = run1.font.small_caps, run2.font.small_caps
    # run2.font.snap_to_grid, run1.font.snap_to_grid = run1.font.snap_to_grid, temp.snap_to_grid
    run2.font.snap_to_grid, run1.font.snap_to_grid = run1.font.snap_to_grid, run2.font.snap_to_grid
    # run2.font.spec_vanish, run1.font.spec_vanish = run1.font.spec_vanish, temp.spec_vanish
    run2.font.spec_vanish, run1.font.spec_vanish = run1.font.spec_vanish, run2.font.spec_vanish
    # run2.font.strike, run1.font.strike = run1.font.strike, temp.strike
    run2.font.strike, run1.font.strike = run1.font.strike, run2.font.strike
    # run2.font.subscript, run1.font.subscript = run1.font.subscript, temp.subscript
    run2.font.subscript, run1.font.subscript = run1.font.subscript, run2.font.subscript
    # run2.font.superscript, run1.font.superscript = run1.font.superscript, temp.superscript
    run2.font.superscript, run1.font.superscript = run1.font.superscript, run2.font.superscript
    # run2.font.underline, run1.font.underline = run1.font.underline, temp.underline
    run2.font.underline, run1.font.underline = run1.font.underline, run2.font.underline
    # run2.font.web_hidden, run1.font.web_hidden = run1.font.web_hidden, temp.web_hidden
    run2.font.web_hidden, run1.font.web_hidden = run1.font.web_hidden, run2.font.web_hidden
    # run2.font.complex_script, run1.font.complex_script = run1.font.complex_script, run2.font.complex_script
    run2.font.complex_script, run1.font.complex_script = run1.font.complex_script, run2.font.complex_script

    run2.font.color.rgb, run1.font.color.rgb = run1.font.color.rgb, run2.font.color.rgb
    run2.font.color.theme_color, run1.font.color.theme_color = run1.font.color.theme_color, run2.font.color.theme_color
    pass
if __name__ == "__main__":
    import copy
    from docx import Document
    filename, userid = "temp.docx", 103562
    file = Document("../upload/" + str(userid) + "/" + filename)
    for p in range(len(file.paragraphs)):
        paragraph = file.paragraphs[p]
        for r in range(len(paragraph.runs)):
            if r<=5:
                run1 = paragraph.runs[r]
                run2 = paragraph.runs[r+1]
                exchangerunformat(run1, run2)
            else:
                file.save("../output/" + str(userid) + "/" + filename)
                exit(0)